#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

#if 1
pthread_mutex_t g_lock1;
pthread_mutex_t g_lock2;
void* threadA(void* arg){
    //线程A加1锁，请求2锁
    pthread_mutex_lock(&g_lock1);
    sleep(1);
    pthread_mutex_lock(&g_lock2);
}
void* threadB(void* arg){
    //线程B加2锁，请求1锁
    pthread_mutex_lock(&g_lock2);
    sleep(1);
    pthread_mutex_lock(&g_lock1);
}
int main(){
    pthread_mutex_init(&g_lock1, NULL);
    pthread_mutex_init(&g_lock2, NULL);
    pthread_t a,b;
    int ret = pthread_create(&a, NULL, threadA, NULL);
    if(ret < 0){
        perror("thread_creat");
        return 0;
    }
    ret = pthread_create(&b, NULL, threadB, NULL);
    if(ret < 0){
        perror("pthread_creat");
        return 0;
    }
    //等待线程
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    //销毁互斥锁
    pthread_mutex_destroy(&g_lock1);
    pthread_mutex_destroy(&g_lock2);
    return 0;
}
#endif

#if 0
#define THREAD_COUNT 1

//代表碗： 0表示没有面， 1表示有面
int g_bowl = 0;

pthread_mutex_t g_lock1;
pthread_mutex_t g_lock2;


void* eat_thread_start(void* arg){
    pthread_mutex_lock(&g_lock2);
    sleep(1);
    pthread_mutex_lock(&g_lock1);

    pthread_mutex_unlock(&g_lock1);
    pthread_mutex_unlock(&g_lock2);
}

void* make_thread_start(void* arg){
    pthread_mutex_lock(&g_lock1);
    sleep(1);
    pthread_mutex_lock(&g_lock2);

    pthread_mutex_unlock(&g_lock2);
    pthread_mutex_unlock(&g_lock1);
}

int main(){
    //1.初始化互斥锁
    pthread_mutex_init(&g_lock1, NULL);
    pthread_mutex_init(&g_lock2, NULL);


    //2.创建吃面的线程 和 做面的线程
    pthread_t eat[THREAD_COUNT], make[THREAD_COUNT];
    for(int i = 0; i < THREAD_COUNT; i++){
        int ret = pthread_create(&eat[i], NULL, eat_thread_start, NULL);
        if(ret < 0){
            perror("pthread_create");
            return 0;
        }

        ret = pthread_create(&make[i], NULL, make_thread_start, NULL);
        if(ret < 0){
            perror("pthread_create");
            return 0;
        }
    }


    //3.等待两种线程
    for(int i = 0; i < THREAD_COUNT; i++){
        pthread_join(eat[i], NULL);
        pthread_join(make[i], NULL);
    }

    //4.销毁互斥锁
    pthread_mutex_destroy(&g_lock1);
    pthread_mutex_destroy(&g_lock2);
    return 0;
}
#endif
